//
//  DownloadViewController.m
//  Emoticon
//
//  Created by ytkjs2 on 2020/3/30.
//  Copyright © 2020 ytk. All rights reserved.
//

#import "DownloadViewController.h"
#import "DownloadViewCell.h"
#import "FLAnimatedImage.h"
#import <Photos/Photos.h>

@interface DownloadViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    CGFloat contentOffsetTemp;
    NSInteger imageIndex;
    UIButton * collectBtn;
}
@end

@implementation DownloadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (_isLongPic) {
        [self hiddenNavigationBarAndTabbar:YES];
        [self addPaperMenu];
    }
    else
        [self addEmoticonMenu];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"DownloadViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"DownloadViewCell"];
    
    [self.view layoutIfNeeded];
    
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_picIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    
    contentOffsetTemp = _picIndex * rScreenWidth;
    
    [self checkCollectStatus:_picIndex];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self hiddenNavigationBarAndTabbar:NO];
}

-(void)addEmoticonMenu
{
    UIView * menu = [[UIView alloc]initWithFrame:CGRectMake(0, rScreenHeight - 100 - navigationBarHeight, rScreenWidth, 50)];
    UIButton * downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [downloadBtn setFrame:CGRectMake(0, 0, 40, 40)];
    downloadBtn.center = CGPointMake(rScreenWidth/4, 25);
    [downloadBtn setImage:[UIImage imageNamed:@"icon_download"] forState:0];
    downloadBtn.imageEdgeInsets = UIEdgeInsetsMake(-15, 12, 0, 0);
    
    downloadBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [downloadBtn setTitle:@"下 载" forState:0];
    [downloadBtn setTitleColor:[UIColor blackColor] forState:0];
    downloadBtn.titleEdgeInsets = UIEdgeInsetsMake(25, -15, 0, 0);
    [downloadBtn addTarget:self action:@selector(downloadAction:) forControlEvents:UIControlEventTouchUpInside];
    [menu addSubview:downloadBtn];
    
    UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 9)];
    line.center = CGPointMake(rScreenWidth/2, 25);
    [line setBackgroundColor:[UIColor blackColor]];
    [menu addSubview:line];
    
    
    collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [collectBtn setFrame:CGRectMake(0, 0, 40, 40)];
    collectBtn.center = CGPointMake(rScreenWidth*3/4, 25);
    [collectBtn setImage:[UIImage imageNamed:@"icon_noCollect"] forState:UIControlStateNormal];
    [collectBtn setImage:[UIImage imageNamed:@"icon_collect"] forState:UIControlStateSelected];
    collectBtn.imageEdgeInsets = UIEdgeInsetsMake(-15, 12, 0, 0);
    collectBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [collectBtn setTitle:@"收 藏" forState:0];
    [collectBtn setTitleColor:[UIColor blackColor] forState:0];
    collectBtn.titleEdgeInsets = UIEdgeInsetsMake(25, -15, 0, 0);
    collectBtn.tag = 100;
    [collectBtn addTarget:self action:@selector(collectPictureAction:) forControlEvents:UIControlEventTouchUpInside];
    [menu addSubview:collectBtn];
    
    [self.view addSubview:menu];
}

-(void)addPaperMenu
{
    UIView * menu = [[UIView alloc]initWithFrame:CGRectMake(10, rScreenHeight - 100, rScreenWidth - 20, 52)];
    menu.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.8];
    [menu.layer setMasksToBounds:YES];
    [menu.layer setCornerRadius:26];
    
    UIButton * preview = [UIButton buttonWithType:UIButtonTypeCustom];
    [preview setFrame:CGRectMake(0, 0, 40, 40)];
    preview.center = CGPointMake((rScreenWidth-20)/6, 25);
    [preview setImage:[UIImage imageNamed:@"icon_preview"] forState:0];
    preview.imageEdgeInsets = UIEdgeInsetsMake(-15, 12, 0, 0);
    
    preview.titleLabel.font = [UIFont systemFontOfSize:11];
    [preview setTitle:@"预 览" forState:0];
    [preview setTitleColor:[UIColor blackColor] forState:0];
    preview.titleEdgeInsets = UIEdgeInsetsMake(25, -15, 0, 0);
    [menu addSubview:preview];
    
    UILabel * line1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 9)];
    line1.center = CGPointMake((rScreenWidth-20)/3, 25);
    [line1 setBackgroundColor:[UIColor blackColor]];
    [menu addSubview:line1];
    
    UIButton * downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [downloadBtn setFrame:CGRectMake(0, 0, 40, 40)];
    downloadBtn.center = CGPointMake((rScreenWidth-20)/2, 25);
    [downloadBtn setImage:[UIImage imageNamed:@"icon_download"] forState:0];
    downloadBtn.imageEdgeInsets = UIEdgeInsetsMake(-15, 12, 0, 0);
    
    downloadBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [downloadBtn setTitle:@"下 载" forState:0];
    [downloadBtn setTitleColor:[UIColor blackColor] forState:0];
    downloadBtn.titleEdgeInsets = UIEdgeInsetsMake(25, -15, 0, 0);
    
    [downloadBtn addTarget:self action:@selector(downloadAction:) forControlEvents:UIControlEventTouchUpInside];
    [menu addSubview:downloadBtn];
    
    UILabel * line2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 9)];
    line2.center = CGPointMake((rScreenWidth-20)*2/3, 25);
    [line2 setBackgroundColor:[UIColor blackColor]];
    [menu addSubview:line2];
    
    
    collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [collectBtn setFrame:CGRectMake(0, 0, 40, 40)];
    collectBtn.center = CGPointMake((rScreenWidth-20)*5/6, 25);
    [collectBtn setImage:[UIImage imageNamed:@"icon_noCollect"] forState:UIControlStateNormal];
    [collectBtn setImage:[UIImage imageNamed:@"icon_collect"] forState:UIControlStateSelected];
    collectBtn.imageEdgeInsets = UIEdgeInsetsMake(-15, 12, 0, 0);
    collectBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [collectBtn setTitle:@"收 藏" forState:0];
    [collectBtn setTitleColor:[UIColor blackColor] forState:0];
    collectBtn.titleEdgeInsets = UIEdgeInsetsMake(25, -15, 0, 0);
    if (_isLoverVc) {
        collectBtn.tag = 102;
    }
    else
        collectBtn.tag = 101;
    
    [collectBtn addTarget:self action:@selector(collectPictureAction:) forControlEvents:UIControlEventTouchUpInside];
    [menu addSubview:collectBtn];
    
    [self.view addSubview:menu];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_isLoverVc) {
        return 2;
    }
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DownloadViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DownloadViewCell" forIndexPath:indexPath];
    NSString * imgUrl = @"";
    if (_isLoverVc) {
        LoverPicModel * model = _dataSource[0];
        NSArray * arr = [NSArray arrayWithArray:model.image];
        imgUrl = [arr[indexPath.item] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
    }
    else
    {
        PicModel * model = _dataSource[indexPath.item];
        imgUrl = [model.image stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    uint8_t c;
    NSData * imgData = [self imageDataFromDiskCacheWithKey:imgUrl];
    [imgData getBytes:&c length:1];
    //判断动图
    if (c == 0x47) {
        cell.img.hidden = YES;
        cell.gif.hidden = NO;
        
        NSURL *url = [NSURL URLWithString:imgUrl];
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            
            [[[SDWebImageManager sharedManager] imageCache] storeImage:image
                                                             imageData:nil
                                                                forKey:url.absoluteString
                                                                toDisk:NO
                                                            completion:nil];
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                if (data != nil) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self animatedImageView:cell.gif
                                           data:data];
                    });
                }
            });
            
        }];
    }
    else
        [cell.img sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"icon_placeholderImage"]];
    
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;//上下行
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;//行距
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);//分别为上、左、下、右
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(rScreenWidth,rScreenHeight);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
     
}

-(void)downloadAction:(UIButton *)btn
{
    NSString * imgStr = @"";
    if (_isLoverVc) {
        LoverPicModel * model = _dataSource[0];
        NSArray * arr = model.image;
        imgStr = arr[imageIndex];
    }
    else
    {
        PicModel * model = _dataSource[imageIndex];
        imgStr = model.image;
    }
    
    NSURL *imgUrl = [NSURL URLWithString:imgStr];
    NSData *data = [NSData dataWithContentsOfURL:imgUrl];
    UIImage *img = [UIImage imageWithData:data];
    
    NSString * localIdentifier = [[NSUserDefaults standardUserDefaults]objectForKey:imgStr];
    
    if (localIdentifier == nil) {
        [self execSavePhoto:img withUrl:imgStr];
    }
    else
    {
        PHAsset * asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil].firstObject;
        if (asset == nil) {
            [self execSavePhoto:img withUrl:imgStr];
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showMessage:@"图片已存在"];
                NSLog(@"图片已存在");
            });
        }
    }
}

- (void)execSavePhoto:(UIImage *)image withUrl:(NSString *)urlStr{
    
    
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    ////异步加载耗时操作
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:data options:nil];
    }completionHandler:^(BOOL success,NSError*_Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
                    if(success && !error){
                        [MBProgressHUD showNormalMessage:@"保存成功"];;
        
                    }else
                        [MBProgressHUD showNormalMessage:@"保存错误"];;
        
                });
          }];
    });

}

-(void)collectPictureAction:(UIButton *)btn
{
    btn.selected = !btn.selected;
    
    if (btn.isSelected) {
        switch (btn.tag) {
            case 100:
                {
                    PicModel * model = _dataSource[imageIndex];
                    [[PictureCache sharedDataBase]insertEmoticonChannerModel:model];
                }
                break;
            case 101:
                {
                    PicModel * model = _dataSource[imageIndex];
                    [[PictureCache sharedDataBase]insertPaperChannerModel:model];
                }
                break;
            case 102:
                {
                    LoverPicModel * model = _dataSource[0];
                    [[PictureCache sharedDataBase]insertLoverChannerModel:model];
                }
                break;
            default:
                break;
        }
    }
    else
    {
        switch (btn.tag) {
            case 100:
                {
                    PicModel * model = _dataSource[imageIndex];
                    [[PictureCache sharedDataBase]deleteEmoticonWithChannelId:model.image_id];
                }
                break;
            case 101:
                {
                    PicModel * model = _dataSource[imageIndex];
                    [[PictureCache sharedDataBase]deletePaperWithChannelId:model.image_id];
                }
                break;
            case 102:
                {
                    LoverPicModel * model = _dataSource[0];
                    [[PictureCache sharedDataBase]deleteLoverWithChannelId:model.image_id];
                }
                break;
            default:
                break;
        }
    }
}

-(void)checkCollectStatus:(NSInteger)selectIndex
{
    imageIndex = selectIndex;
    
    
    if (_isLongPic) {
        if (!_isLoverVc) {
            PicModel * model = _dataSource[imageIndex];
            if ([[PictureCache sharedDataBase]isExistPaperWithChannelId:model.image_id]) {
                collectBtn.selected = YES;
            }
            else
                collectBtn.selected = NO;
        }
        else
        {
            LoverPicModel * model = _dataSource[0];
            if ([[PictureCache sharedDataBase]isExistLoverWithChannelId:model.image_id]) {
                collectBtn.selected = YES;
            }
            else
                collectBtn.selected = NO;
        }
    }
    else
    {
        PicModel * model = _dataSource[imageIndex];
        if ([[PictureCache sharedDataBase]isExistEmoticonWithChannelId:model.image_id]) {
            collectBtn.selected = YES;
        }
        else
            collectBtn.selected = NO;
        
    }
//    PictureModel * model = self.dataSource[selectIndex];
//    if ([[PaperWallCache sharedDataBase]isExistNormalIMGWithThumb:model.thumb]) {
//        collectBtn.selected = YES;
//    }
//    else
//        collectBtn.selected = NO;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat offset = scrollView.contentOffset.x - contentOffsetTemp;
    
    if (offset >= rScreenWidth) {
        _picIndex += offset/rScreenWidth;
    }
    if (offset <= -rScreenWidth) {
        _picIndex += offset/rScreenWidth;
    }
    
    contentOffsetTemp = scrollView.contentOffset.x;
    
    [self checkCollectStatus:scrollView.contentOffset.x/rScreenWidth];
}

- (void)animatedImageView:(FLAnimatedImageView *)imageView data:(NSData *)data {
    
    FLAnimatedImage *gifImage = [FLAnimatedImage animatedImageWithGIFData:data];
    imageView.animatedImage   = gifImage;
}

- (NSData *)imageDataFromDiskCacheWithKey:(NSString *)key {
    
    NSString *path = [[[SDWebImageManager sharedManager] imageCache] defaultCachePathForKey:key];
    return [NSData dataWithContentsOfFile:path];
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    [color setFill];
    UIRectFill(rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

-(void)hiddenNavigationBarAndTabbar:(BOOL)isHidden
{
    if (isHidden) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    }
    else
    {
        [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:APP_THEME_COLOR] forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setShadowImage:nil];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
